'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册
    async registry() {
        const { ctx,service } = this;
        //1. 先获取参数
        //2. 容错处理   正则验证
        //3. 排重
        //4. 注册   密码改成加密的
        let {phone,password,role} = ctx.request.body;
        if(/^\d{11}$/.test(phone) && password && role){
            let target = await service.user.selectUser(phone);
            if(target.length){
                //已经存在
                ctx.body = {
                    code:3,
                    msg:'此手机号已存在'
                }
            }else{
                //不存在
                try{
                    let hmcPwd = ctx.helper.hmc(password);
                    await service.user.registry(phone,hmcPwd,role);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //登录
    async login() {
        //1.获取前端传递的参数
        //2.容错处理
        //3.查询是否有符合条件的数据  密码加密
        let {ctx,service} = this;
        console.log(ctx.params);
        let {phone,password} = ctx.request.body;


        if(/^\d{11}$/.test(phone) && password){
            let hmcPwd = ctx.helper.hmc(password);
            let list = await service.user.login(phone,hmcPwd);
            if(list.length){
                let token = jwt.sign({phone,password},'lixd',{expiresIn:60*60*4});

                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token,
                    role:list[0].role
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = UserController;
